<template>
    <div class="login-container">
        <div class="background-overlay"></div>
        <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px" label-position="left"
            @submit.prevent="login">
            <h2>用户登录</h2>
            <el-form-item label="用&ensp;户&ensp;名" prop="username">
                <el-input v-model="loginForm.username" />
            </el-form-item>

            <el-form-item label="密&emsp;&emsp;码" prop="password" class="password-input">
                <el-input v-model="loginForm.password" type="password" show-password />
            </el-form-item>

            <el-form-item label="验&ensp;证&ensp;码" prop="captcha" class="captcha">
                <div style="display: flex; align-items: center;">
                    <el-input v-model="loginForm.captcha" style="flex-grow: 1; margin-right: 12px;" />
                    <img :src="captchaImage" alt="验证码" @click="fetchCaptcha" class="captcha-img"
                        style="height: 60px; width: 150px; cursor: pointer;" />
                </div>
            </el-form-item>
            <div class="button-box">
                <el-button type="primary" native-type="submit">登录</el-button>
                <el-button link @click="goToRegister">没有账号？立即注册</el-button>
            </div>
        </el-form>
    </div>
</template>
<script setup>
import { ref } from 'vue';
import api from '@/services/api';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();

const loginForm = ref({
    username: '',
    password: '',
    captcha: '',
    imgToken: ''
});

const captchaImage = ref('');

// 表单引用
const loginFormRef = ref();

// 表单验证规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 15, message: '用户名长度在3到15个字符之间', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码至少6位', trigger: 'blur' }
    ],
    captcha: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { len: 4, message: '请输入4位验证码', trigger: 'blur' }
    ]
};

// 获取验证码
const fetchCaptcha = async () => {
    try {
        const response = await api.captcha();
        captchaImage.value = response.data.base64Image;
        loginForm.value.imgToken = response.data.token;
    } catch (err) {
        console.error('获取验证码失败:', err);
        ElMessage.error('获取验证码失败');
    }
};

// 登录逻辑
const login = async () => {
    const valid = await loginFormRef.value.validate().catch(err => false);
    if (valid) {
        try {
            const response = await api.login(
                loginForm.value.username,
                loginForm.value.password,
                loginForm.value.captcha,
                loginForm.value.imgToken
            );
            localStorage.setItem('token', response.data.token);
            ElMessage.success('登录成功');
            router.push('/banks');
        } catch (err) {
            loginForm.value.captcha = '';
            fetchCaptcha();
            console.error('登录失败:', err);
            
            // 根据错误类型显示不同提示
            if (err.response?.data?.message?.includes('验证码')) {
                ElMessage.error('验证码错误');
            } else if (err.response?.status === 500) {
                ElMessage.error('账号或密码错误');
            } else {
                ElMessage.error('登录失败，请重试');
            }
        }
    } else {
        ElMessage.warning('请正确填写表单信息');
        return false;
    }
};

const goToRegister = () => {
    router.push('/register');
};

// 初始化加载验证码
fetchCaptcha();
</script>

<style scoped>
.login-container {
    position: relative;
    max-width: 450px;
    width: 90%;
    margin: 12vh auto;
    padding: 40px 35px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 24px;
    box-shadow: 0 16px 32px rgba(0, 0, 0, 0.12);
    backdrop-filter: blur(8px);
}

h2 {
    text-align: center;
    margin-bottom: 30px;
    color: #2c3e50;
    font-weight: 650;
    font-size: 28px;
    letter-spacing: 1px;
}

.el-form :deep(.el-form-item__label) {
    font-weight: 550;
    color: #4a5568;
}

.captcha,
.password-input {
    margin-bottom: 4px;
}


.captcha :deep(.el-form-item__label) {
    line-height: 60px;
}

.captcha :deep(.el-form-item__error) {
    top: 46px;
}

.el-button--primary {
    padding: 14px 28px;
    border-radius: 12px;
    font-size: 16px;
    letter-spacing: 0.5px;
    box-shadow: 0 4px 6px rgba(64, 158, 255, 0.15);
    width: 50%;
    margin-bottom: 10px;
}

.el-button--primary:hover {
    transform: translateY(-1px);
    box-shadow: 0 6px 12px rgba(64, 158, 255, 0.25);
}

.el-button--text {
    margin-top: 18px;
    font-size: 14px;
}

.button-box {
    display: flex;
    flex-direction: column;
    align-items: center;
}
</style>
